package sz.szsmk.citizencard.ui.adapter;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.DefaultLayoutHelper;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.UserHeadViewBinding;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.QueryAllFunctionNewRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryNgFinanceRes;
import sz.szsmk.citizencard.model.network.bean.response.SignInRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.ui.activity.ChargeActivity;
import sz.szsmk.citizencard.ui.activity.SignInActivity;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.model.network.bean.response.CouponListBean;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.BlurringView;
import sz.szsmk.citizencard.widget.GlideCircleTransform;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/7 14:32
 * description:我的头部适配器
 */
public class UserHeadAdapter extends DelegateAdapter.Adapter<UserHeadAdapter.UserHeadHolder> {

    private FragmentActivity mContext;
    private LayoutHelper mDefaultLayoutHelper;
    private IUserInfo.UserExBean mUserEx;
    private SignInRes userCreditBean;
    private String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1529572813554&di=a40a0385f7e0524dd2ceca88c93aba08&imgtype=0&src=http%3A%2F%2Fp1.qhimgs4.com%2Ft01a0c0dd4947f07eb5.jpg";

    private BlurringView mBlurringView;
    private String data;
    private IUserInfo.UserExBean userExBean = new IUserInfo.UserExBean();
    private ImageView headIcon;
    private String nick_name;
    private String url1;
    private String mobile;
    private UserHeadViewBinding binding;
    private QueryNgFinanceRes queryNgFinanceRes;
    private BaseInterface baseInterface;
    private View backView;

    public UserHeadAdapter(FragmentActivity activity, DefaultLayoutHelper headHelper, View backView) {
        mContext = activity;
        mDefaultLayoutHelper = headHelper;
        this.backView = backView;
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mDefaultLayoutHelper;
    }

    @Override
    public int getItemCount() {
        return 1;
    }


    @Override
    public int getItemViewType(int position) {
        return R.layout.user_head_view;
    }

    public interface BaseInterface {
        public void onClick(View view, String url, String syslabl, int need_header, String s, QueryAllFunctionNewRes.ClassListBean.FunctionListBean bean);
    }

    public void setBaseInterface(BaseInterface baseInterface) {
        this.baseInterface = baseInterface;
    }

    @Override
    public UserHeadHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return UserHeadHolder.creat(parent);
    }

    @Override
    public void onBindViewHolder(UserHeadHolder holder, int position) {
        loadItemData(position, holder.binding);
    }

    public static String settingphone(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }

    private void loadItemData(int position, UserHeadViewBinding binding) {


        binding.apphomeRealnameLl.setVisibility(View.INVISIBLE);

        if (!Constant.isLogin) {
            binding.userHeadTv.setText("未登录，请登录");
        }
        if (mUserEx == null) {
            binding.userInfoLl.setVisibility(View.GONE);
            binding.userHeadTv.setVisibility(View.VISIBLE);
            binding.userHeadTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JumpUtils.jump(mContext, "login", 0);
                }
            });
            binding.llAccumulatePoints.setOnClickListener(v -> {
                JumpUtils.jump(mContext, "login", 0);
            });
            binding.llMycoupon.setOnClickListener(v -> {
                //优惠券
                MessageEvent message = new MessageEvent(MessageEvent.CODE_USERBEHAVIOR);
                message.setData(51);
                EventBus.getDefault().post(message);
                Bundle bundle = new Bundle();
                bundle.putSerializable("couponListBean",couponListBean);
                JumpUtils.jumptoNatvie(mContext, "myCoupon", 0, bundle);//discountCouponListActivity
            });

            binding.llGuihuascore.setOnClickListener(v->{
                JumpUtils.jump(mContext, "login", 0);
            });

            binding.tvAccumulatePoints.setText("***");
            binding.tvMyCoupon.setText("***");
            binding.tvGuihuascore.setText("***");
            binding.finance.setText("***");

        } else {
            binding.userInfoLl.setVisibility(View.VISIBLE);
            binding.userHeadTv.setVisibility(View.GONE);
            mobile = mUserEx.getMobile();
            nick_name = mUserEx.getNick_name();
            url1 = mUserEx.getPhoto_url();
            if(appHomeCardBean!=null && appHomeCardBean.getLevel().equals("L1") && appHomeCardBean.getLevel().equals("L2")){
                binding.tvGuihuascore.setText("L3未认证");
            }else{
                if(ACache.get(mContext).getAsString("ghfScore")==null){
                    binding.tvGuihuascore.setText("未授权");
                    binding.tvGuihuascore.setTextColor(mContext.getResources().getColor(R.color.color_28ffffff));
                }else{
                    binding.tvGuihuascore.setText(ACache.get(mContext).getAsString("ghfScore"));
                }
            }


            //跳转到授权页面
            QueryAllFunctionNewRes.ClassListBean.FunctionListBean bean = new  QueryAllFunctionNewRes.ClassListBean.FunctionListBean();
            bean.setFunction_id(3);
            bean.setFunction_name("桂花分");
            bean.setResource_page_id(3);
            bean.setLink_url("proto:osmanthus");
            bean.setSys_label("GUIHUAFEN");
            bean.setNeed_header(1);
            bean.setModularId(2);

            binding.tvGuihuascore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if( appHomeCardBean.getLevel().equals("L1") && appHomeCardBean.getLevel().equals("L2")){
                        JumpUtils.jump(mContext, "RealNameActivity", 0);
                    }else{
                        if(ACache.get(mContext).getAsString("ghfScore")==null){
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.TYPE, "ghf");
                            bundle.putString(Constant.ID_NAME, Constant.USER_NAME);
                            JumpUtils.jumptoNatvie(mContext, "applicationAuthorActivity", 0, bundle);
                        }else{
                            baseInterface.onClick(v, url, bean.getSys_label(), bean.getNeed_header(),bean.getFunction_id()+"",bean);
                        }
                    }
                }
            });




            if(queryNgFinanceRes!=null){
                binding.finance.setText(queryNgFinanceRes.getAssets()+"元");
            }else{
                binding.finance.setText("0.00元");
            }

            if (url1 != null) {
                Glide.with(mContext)
                        .load(url1)
                        .override(100, 40)
                        .transform(new GlideCircleTransform(mContext))
                        .placeholder(R.drawable.user_icon)
                        .into(binding.userUserinfo);
            }
            if (mobile != null) {
                binding.userPhone.setText(settingphone(mobile));
            }
            if (nick_name != null) {
                binding.userName.setText(nick_name + "");
            } else {
                binding.userName.setText("未命名");
            }

            binding.rlWallet.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    String access_token = ACache.get(mContext).getAsString("access_token");
                    bundle.putString("url", Constant.BASE_URL + "app-front-end/#/wallet/main");
                    JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                }
            });

            binding.rlFinance.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MessageEvent message = new MessageEvent(MessageEvent.CODE_OPENNG);
                    EventBus.getDefault().post(message);
                }
            });

            //设置 积分和优惠券
            if(userCreditBean!=null){
                binding.tvAccumulatePoints.setText(userCreditBean.getCredit()+"");
            }else{
                binding.tvAccumulatePoints.setText("0");
            }
            if(couponListBean!=null){
                int allCount = 0;
                for(int i=0;i<couponListBean.getData().size();i++){
                    allCount+= couponListBean.getData().get(i).getUsedCount();
                }
                binding.tvMyCoupon.setText(allCount+"");
            }else {
                binding.tvMyCoupon.setText("0");
            }

            binding.llAccumulatePoints.setOnClickListener(v -> {
                MessageEvent message = new MessageEvent(MessageEvent.CODE_USERBEHAVIOR);
                message.setData( 45);
                EventBus.getDefault().post(message);
                //打开积分明细界面
                Intent intent = new Intent(mContext, SignInActivity.class);
                mContext.startActivity(intent);
            });
            binding.llMycoupon.setOnClickListener(v -> {
                MessageEvent message = new MessageEvent(MessageEvent.CODE_USERBEHAVIOR);
                message.setData(51);
                EventBus.getDefault().post(message);
                //我的优惠券
                Bundle bundle = new Bundle();
                bundle.putSerializable("couponListBean",couponListBean);//discountCouponListActivity
                JumpUtils.jumptoNatvie(mContext, "myCoupon", 0, bundle);

            });

            binding.llGuihuascore.setOnClickListener(v->{
                //跳转桂花分

                Bundle bundle = new Bundle();
                String murl = Constant.SZ_URL +"?"+ Constant.EXTENT;
                bundle.putString("url", murl);
                bundle.putString(Constant.TITLE, "桂花分");
                JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
            });



        }


        if(appHomeCardBean!=null){
            if (!StringUtils.isBlank(appHomeCardBean.getLevel())) {
                binding.level.setText(appHomeCardBean.getLevel());
                switch (appHomeCardBean.getLevel()) {
                    case "L1":
                        binding.levelDesc.setText("已完成登录注册，升级L2");
                        break;
                    case "L2":
                        binding.levelDesc.setText("已完成实名认证，升级L3");
                        break;
                    case "L3":
                        String levelDesc = appHomeCardBean.getLevelDesc();
                        binding.apphomeUpdataTv.setVisibility(View.GONE);
                        binding.levelDesc.setText("已完成L3认证");
                        break;
                }
                binding.apphomeRealnameLl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("appHomeCardBean", appHomeCardBean);
                        JumpUtils.jumptoNatvie(mContext, "RealNameActivity", 0, bundle);
                    }
                });
                binding.apphomeRealnameLl.setVisibility(View.VISIBLE);
            }
        }



        binding.userSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JumpUtils.jump(mContext, "setting", 0);
            }
        });
        binding.userUserinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("nickname", nick_name);
                bundle.putString("phone", mobile);
                bundle.putString("url1", url1);
                JumpUtils.jumptoNatvie(mContext, "userinfo", 0, bundle);
//                JumpUtils.jump(mContext, "userinfo", 0);
            }
        });

    }

    public void invalidateHead() {

    }

    public void setListData(IUserInfo.UserExBean userEx) {
        mUserEx = userEx;
    }

    public void setQueryNgFinanceRes(QueryNgFinanceRes res){
        queryNgFinanceRes=res;
    }

    public void setUserCreditBean(SignInRes userCreditBean){
        this.userCreditBean = userCreditBean;
    }

    AppHomeCardBean appHomeCardBean;
    public void setLvdata(AppHomeCardBean lvdata) {
        this.appHomeCardBean = lvdata;
    }

    public void setData(String data) {
        this.data = data;
        if (data.equals("")) {
            this.data = data;
        } else {
            this.data = data;
            userExBean = new Gson().fromJson(data, IUserInfo.UserExBean.class);
        }
    }

    CouponListBean couponListBean;
    public void setCounpon(CouponListBean couponListBean) {
        this.couponListBean = couponListBean;
        notifyDataSetChanged();
    }

    static class UserHeadHolder extends RecyclerView.ViewHolder {

        private UserHeadViewBinding binding;

        public static UserHeadHolder creat(ViewGroup parent) {
            UserHeadViewBinding binding = UserHeadViewBinding
                    .inflate(LayoutInflater.from((parent.getContext())), parent, false);
            return new UserHeadHolder(binding);
        }

        public UserHeadHolder(UserHeadViewBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
